import Router from '../../../utils/router.js'
import authorize from '../../../utils/authorize'
import util from '../../../utils/util.js'
import base from '../../../config/base.js';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    share: {
      type: Object,
      value: {
        isShow: false,
        animate: false,
        bybsid: ''
      }
    },
    paymask: {
      type: Object,
      value: {}
    },
    user_info: {
      type: Object
    },
    activity: {
      type: Object
    },
    tempFilePathAvatar: {
      type: String
    },
    avatar: {
      type: String
    },
    store_id: {
      type: String
    },
    name: {
      type: String
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    imagePath: [],
    flag: false,
    canvasWH: {
      w: 375,
      h: 573
    },
    shareJSON: {
      bgImg: {//背景图
        url: base.static + 'store/sharefiend-bg8.png',
        w: 375, h: 573, x: 0, y: 0,
      },
      ewmImg: {//二维码位置
        w: 100, h: 100, x: 135, y: 445
      },
      txImg: {//微信头像
        w: 65, h: 65, x: 23, y: 20
      },
      invite_name: {
        x: 103, y: 45, size: 20
      }
    },
    avatar: '',
    tempFilePathAvatar: '',
    name: '',
  },

  ready(){
    let v = null;
    try {
      v = util.compareVersion('2.0.7');
    }catch(e){
      console.log(e);
    }

    let properties = this.properties;
    this.setData({
      v,
      user_info: properties.user_info,
      activity: properties.activity,
      tempFilePathAvatar: properties.tempFilePathAvatar,
      avatar: properties.avatar,
      name: properties.name,
      store_id: properties.store_id
    });
    let name = 'scope.writePhotosAlbum'
    wx.getSetting({
      success: (res) => {
        let authsave = '';
        let arrAuthSetting = Object.getOwnPropertyNames(res.authSetting);
        // 提示过用户授权 但是没有通过
        if (arrAuthSetting.indexOf(name) > -1) {
          if (res.authSetting[name]) {
            authsave = 1;
          } else {
            if (v != -1) {
              authsave = 0;
            } else {
              authorize('writePhotosAlbum');
            }
          }
        } else {
          authsave = -1;
        }
        this.setData({
          authsave
        });
      }
    });

  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 阻止冒泡事件
     */
    catchtap: function () { },
    /**
     * 取消弹框
     */
    hidemask: function () {
      var that = this,
        share = that.data.share,
        time = 50;
      that.data.flag = false;
      // share.isShow = true;
      share.animate = false;
      // that.setData({
      //   share: share,
      //   showcard: false

      // });
      // setTimeout(function () {
        share.isShow = false;
        that.setData({
          share: share,
          showcard: false
        });
      // }, time);
    },
    opensetting(e){
      let authsave = 0;
      if (e.detail.authSetting && e.detail.authSetting['scope.writePhotosAlbum']) {
        authsave = 1;
        // this.downIMG();
      } else {
        authsave = 0;
      }
      this.setData({
        authsave
      });
    },
    showCard() {//分享盆友圏 出卡片
      var _this = this;
      if(_this.data.flag){
        return;
      }
      _this.data.flag = true;
      //直接生成图片
      wx.showLoading({
        title: '图片生成中',
      })
      _this.createNewImg();
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: "ease",
        delay: 0
      })
      _this.frendanimate = animation
      animation.translateY(500).step()
      _this.setData({
        frendanimate: animation.export(),
        showcard: true,
        imagePath: ''
      })
      setTimeout(function () {
        animation.translateY(0).step()
        _this.setData({
          frendanimate: animation.export(),
        })
        wx.showLoading({
          title: '图片生成中',
        })
      }.bind(_this), 100)
    },
    createNewImg() {//开始画图
      var _this = this;
      let share = _this.data.share;
      share.isShow = false;
      _this.setData({
        share: share,
      })
      let shareJSON = _this.data.shareJSON;
      var context = wx.createCanvasContext('myCanvas', 'this');
      //清除  画布 内容
      context.clearRect(0, 0, _this.data.canvasWH.w, _this.data.canvasWH.h);
      _this.setWxbg(context)
    },
    setWxbg(context) {
      let shareJSON = this.data.shareJSON;
      let _this = this,
        bgImg = shareJSON.bgImg;
      try {
        var path = bgImg.url;
        wx.downloadFile({
          url: path,
          success(res) {
            if(res.statusCode==200){
              context.drawImage(res.tempFilePath, bgImg.x, bgImg.y, bgImg.w, bgImg.h);
            }
            _this.setWxtx(context)
          }, fail(res) {
            _this.errorDraw('背景图下载失败');
          }
        })
      } catch (err) {
        console.log('setWxbg', err);
      }
    },
    setWxma(context) {
      let _this = this;
      let shareJSON = this.data.shareJSON;
      let store_id = _this.data.store_id;
      let ewmImg = shareJSON.ewmImg;
      try {
        let user_info = _this.data.user_info,
          auth_token = wx.getStorageSync('auth_token'),
          path = encodeURIComponent('pages/store/index?store_id=' + store_id + '&sharerecord=storecode'),
          url = base.apiUrl + '/getCustomerQrCode?' + '&path=' + path + '&scene=1012' + '&auth_token=' + auth_token;
        wx.downloadFile({
          url: url,
          success(res) {
            if (res.statusCode == 200) {
              context.drawImage(res.tempFilePath, ewmImg.x, ewmImg.y, ewmImg.w, ewmImg.h);
              _this.setWxtext(context);
            }
            else if (res.statusCode == 401) {
              _this.errorDraw('登录过期');
              setTimeout(()=>{
                const currentPages = getCurrentPages();
                const fromPageUrl = '/' + currentPages[currentPages.length - 1].__route__ || '';
                Router.go('register', `to=${encodeURIComponent(fromPageUrl)}`);
              }, 500)
            }
          }, fail(res) {
            _this.errorDraw('小程序码绘制失败');
          }
        })
      } catch (err) {
        console.log('setWxma', err);
      }
    },
    setWxtx(context) {
      let shareJSON = this.data.shareJSON;
      let _this = this,
        txImg = shareJSON.txImg;
      try{
        wx.downloadFile({
          url: _this.data.avatar,
          success(res) {
            if(res.statusCode==200){
              _this.circleImg(context, res.tempFilePath, txImg.x, txImg.y, txImg.w, txImg.h, txImg.w)
              _this.setWxma(context)
            }
          }, fail(res) {
            context.drawImage(_this.data.tempFilePathAvatar, txImg.x, txImg.y, txImg.w, txImg.h);
            _this.setWxma(context)
          }
        })
      }catch(err) {
        console.log('setWxtx', err);
      }
    },
    circleImg(context, img, x, y, r) { //切圆方法
      let _this = this;
      try{
        context.save();
        context.beginPath();
        r = r / 2;//半径
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        context.arc(cx, cy, r, 0, 2 * Math.PI);
        context.clip();
        context.drawImage(img, x, y, d, d);
        context.restore();
      }catch(err) {
        console.log('circleImg', err);
        _this.errorDraw('头像切圆失败');
      }
    },
    setWxtext(context) {
      let shareJSON = this.data.shareJSON
      let _this = this,
        invite_name = shareJSON.invite_name;
      try{
        invite_name.txt = _this.data.name;
        _this.setWxtextfn(context, invite_name);
      } catch (err) {
        console.log('setWxtext', err);
        _this.errorDraw();
      }
    },
    setWxtextfn(context, obj){
      let _this = this;
      let canvasWH = _this.data.canvasWH;
      try{
          context.setFontSize(obj.size);
          context.fillText(obj.txt, obj.x, obj.y);
        _this.last(context)
      } catch (err) {
        console.log('setWxtext', err);
        _this.errorDraw('绘制名称失败');
      }
    },
    last(context) {
      let _this = this;
      try{
        context.draw(false, function (e) {
          wx.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: function (res) {
              wx.hideLoading()
              _this.setData({
                imagePath: res.tempFilePath
              });
            }, fail(res) {
              _this.errorDraw();
            }
          })
        })
      } catch (err) {
        console.log('last', err);
        _this.errorDraw();
      }
    },
    errorDraw(str) {
      wx.hideLoading()
      wx.showToast({
        title: str || '图片生成失败，请重试！',
        icon: 'none'
      })
    },
    downImage() {//保存下载
      var _this = this;
      authorize('writePhotosAlbum', (b) => {
        if (b) {
          _this.downIMG();
        }else{
          if (_this.data.v != -1) {
            wx.showToast({
              title: '您未授权保存到相册功能，设置后正常使用',
              icon: 'none'
            })
            this.setData({
              authsave: 0
            });
          } else {
            wx.showModal({
              title: '授权提示',
              content: '您未授权保存到相册功能，设置后正常使用',
              showCancel: false,
              success: res => {
                wx.openSetting({
                  success: res => { },
                  fail: res => { }
                })
              }
            })
          }
        }
      })
    },
    downIMG(){
      let _this = this;
      wx.saveImageToPhotosAlbum({
        filePath: _this.data.imagePath,
        success() {
          wx.showToast({
            title: '已保存至相册',
            icon: 'none'
          })
        }
      })
      _this.setData({
        flag: false
      })
    },
    hidecard() {//隐藏卡片
      var _this = this;
      wx.hideLoading();
      _this.setData({
        showcard: false
      })
    },
  }
})
